﻿using Core.DataAccess.Model.Projects;
using Core.Framework.Redis.Queue_Helper;
using Core.Framework.Util;
using Core.IBusiness.IUserModule;
using System;
using System.Linq;

namespace Core.Business.UserModule
{
    /// <summary>
    /// 1. project 需要补充  可更新 projecttoken
    /// </summary>
    public class ProjectUsers : IProjectUser
    {
        public Tuple<bool, ProjectUser> GetUserInfoByToken(string token)
        {
            var userInfo 
                = RedisQueueHelper.HashGet(RedisQueueHelperParameter.ProjectUserLogin, token);

            var model = ((string) userInfo).TryToEntity<ProjectUser>();

            if (model != null)
            {
                if (model.EndTime > DateTime.Now)
                    return new Tuple<bool, ProjectUser>(true, model);
                else
                    return new Tuple<bool, ProjectUser>(false, model);
            }

            return new Tuple<bool, ProjectUser>(false,null);

        }

        public Tuple<ProjectUser, bool> Login(string user, string password, int hour)
        {

            using (var context = new ProjectContext())
            {
                var userInfo =
                    context.ProjectUser.Where(a =>
                        a.Phone == user &&
                        a.Pass == Md5Helper.Hash(password)
                    ).FirstOrDefault();

                if (null != userInfo && userInfo.Id > 0)
                {
                    // 同一用户 只保存一个token
                    this.OutLogin(userInfo.Token);

                    // 用户临时token
                    userInfo.Token = Md5Helper.Hash(Guid.NewGuid().ToString());

                    // 过期时间
                    userInfo.EndTime = DateTime.Now.AddHours(hour);

                    // 更新用户token
                    context.SaveChanges();

                    // 写入缓存
                    RedisQueueHelper
                        .HashSet(RedisQueueHelperParameter.ProjectUserLogin, userInfo.Token, userInfo.TryToJson());

                    return
                        new Tuple<ProjectUser, bool>(userInfo, true);
                }

                return
                    new Tuple<ProjectUser, bool>(null, false);
            }

        }

        public Tuple<ProjectUser, bool> LoginByToken(string token, string password, int hour)
        {

            var tuple = this.GetUserInfoByToken(token);

            if (tuple.Item2 != null)
                if (tuple.Item2.Pass == Md5Helper.Hash(password))
                {
                    // 过期时间
                    tuple.Item2.EndTime = DateTime.Now.AddHours(hour);

                    // 写入缓存
                    RedisQueueHelper
                        .HashSet(RedisQueueHelperParameter.ProjectUserLogin, tuple.Item2.Token, tuple.Item2.TryToJson());

                    return new Tuple<ProjectUser, bool>(tuple.Item2, true);
                }

            using (var context = new ProjectContext())
            {
                var userInfo =
                    context.ProjectUser.Where(a =>
                        a.Token == token &&
                        a.Pass == Md5Helper.Hash(password)
                    ).FirstOrDefault();

                if (null != userInfo && userInfo.Id > 0)
                {
                    // 过期时间
                    userInfo.EndTime = DateTime.Now.AddHours(hour);

                    // 写入缓存
                    RedisQueueHelper
                        .HashSet(RedisQueueHelperParameter.ProjectUserLogin, userInfo.Token, userInfo.TryToJson());

                    return
                        new Tuple<ProjectUser, bool>(userInfo, true);
                }

                return
                    new Tuple<ProjectUser, bool>(null, false);

            };
        }

        public void OutLogin(string token)
        {
            RedisQueueHelper.HashDelete(RedisQueueHelperParameter.ProjectUserLogin, token);
        }

        public Tuple<bool, ProjectUser, string> Reg(ProjectUser model)
        {

            if (model == null)
                return new Tuple<bool, ProjectUser, string>(false, model, "数据为NULL");

            var result = model.IsValid(IsValidEnum.reg);
            if (!result.Item1)
                return new Tuple<bool, ProjectUser, string>(result.Item1,model,result.Item2);

            using (var context = new ProjectContext())
            {
                var userInfo =
                    context.ProjectUser.Where(a =>
                        a.Phone == model.Phone
                    ).Select(a => new { userid = a.Id }).FirstOrDefault();

                if (userInfo?.userid > 0)
                    return new Tuple<bool, ProjectUser, string>(false,model,"该账号已注册");

                model.AddTime = DateTime.Now;
                model.Pass = Md5Helper.Hash(model.Pass);
                model.Token = Md5Helper.Hash($"{model.Phone}_z_%^&*");
                context.ProjectUser.Add(model);
                context.SaveChanges();
                return new Tuple<bool, ProjectUser, string>(true, model, "注册成功"); ;
            };
        }

        public ProjectUser UpdateUserInfo(ProjectUser model)
        {
            using (var context = new ProjectContext())
            {
                var userInfo = context.ProjectUser
                    .Where(a => a.Phone == model.Phone && a.Token == model.Token)
                    .FirstOrDefault();

                if (userInfo != null)
                {
                    userInfo.Combine(model, "Id", "id", "AddTime");
                    context.SaveChanges();
                    return model;
                }

                return null;

            };
        }
    }
}
